package handler

import (
	"context"
	"errors"
	"gomicro-sharemod/services/common-service/models"
	"gomicro-sharemod/services/common-service/tools"
	"math"
	"strings"

	pbParams "gomicro-sharemod/services/common-service/proto/commonParams"
	pbResult "gomicro-sharemod/services/common-service/proto/commonResult"
	pbRegion "gomicro-sharemod/services/common-service/proto/region"
)

/*
 +----------------------------------------------------------------------
 + Title        : RegionHandler
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2019-08-08
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 区域处理
 +----------------------------------------------------------------------
*/

type RegionHandler struct{}

/**
 * 新增
 *
 * @param uint32 Pid --------------------------非必传,父级Id
 * @param string Name -------------------------必传,名称
 * @param uint32 Level ------------------------非必传,级别
 * @param uint32 Sort -------------------------非必传,排序
 * @param int32 IsHot -------------------------非必传,位置
 * @return *pbResult.Result error
 * @author huwl
 */
func (e *RegionHandler) AddRegion(ctx context.Context, req *pbRegion.AddRegionRequest, rsp *pbResult.Result) error {
	name := req.Name

	if name == "" {
		return errors.New("名称不能为空")
	}

	result, err := models.Region{}.Add(&models.Region{
		Pid:   uint16(req.Pid),
		Name:  name,
		Level: uint8(req.Level),
		Sort:  uint8(req.Sort),
		IsHot: int8(req.IsHot),
	})
	if err != nil {
		return err
	}
	if result <= 0 {
		return errors.New("新增区域失败")
	}

	rsp.Code = 200
	rsp.Msg = "新增区域成功"
	return nil
}

/**
 * 区域详情
 *
 * @param int id ----------------------------------------------------------------------------必传，区域ID
 * @return Region error
 * @author huwl
 */
func (e *RegionHandler) RegionDetail(ctx context.Context, req *pbParams.DetailRequest, rsp *pbRegion.RegionResponse) error {
	id := req.Id

	if id <= 0 {
		return errors.New("区域ID错误")
	}

	//获取区域信息
	region := models.Region{}
	result, err := models.Region{}.GetResultByPrimaryKey(&region, id)
	if err != nil {
		return err
	}
	if result <= 0 {
		return errors.New("区域信息错误")
	}

	rsp.Region = &pbRegion.Region{
		Id:    uint32(region.Id),
		Pid:   uint32(region.Pid),
		Name:  region.Name,
		Level: uint32(region.Level),
		Sort:  uint32(region.Sort),
		IsHot: int32(region.IsHot),
	}
	return nil
}

/**
 * 区域列表
 *
 * @param int Id ----------------------------------------------------------------------------非必传，区域ID
 * @param string Ids ------------------------------------------------------------------------非必传，区域ID支持多个
 * @param string Pid ------------------------------------------------------------------------非必传，父级ID
 * @param string Pids -----------------------------------------------------------------------非必传，父级ID支持多个
 * @param string Name -----------------------------------------------------------------------非必传，名称
 * @param int Level -------------------------------------------------------------------------非必传，级别
 * @param string IsHost ---------------------------------------------------------------------非必传，是否热门
 * @param string SortType -------------------------------------------------------------------非必传，排序方式
 * @param string SortField ------------------------------------------------------------------非必传，排序字段
 * @param string PageSize -------------------------------------------------------------------非必传，条数
 * @param string Page -----------------------------------------------------------------------非必传，页码
 * @return Code Page Total PageSize PageTotal Regions error
 * @author huwl
 */
func (e *RegionHandler) RegionList(ctx context.Context, req *pbRegion.QueryRegionRequest, rsp *pbRegion.RegionListResponse) error {
	params := map[string]interface{}{}

	page := req.Page
	pageSize := req.PageSize
	sortType := req.SortType
	sortField := req.SortField

	if req.Id > 0 {
		params["id"] = req.Id
	}
	if req.Ids != "" {
		params["id IN (?)"] = tools.IntSplit(strings.TrimRight(req.Ids, ","), ",")
	}
	if req.Pid != "all" {
		params["pid"] = req.Pid
	}
	if req.Pids != "" {
		params["pid IN (?)"] = tools.IntSplit(strings.TrimRight(req.Pids, ","), ",")
	}
	if req.Name != "" {
		params["name"] = req.Name
	}
	if req.Level > 0 {
		params["level"] = req.Level
	}
	if req.IsHot != "all" {
		params["is_hot"] = req.IsHot
	}
	if page <= 0 {
		page = 1
	}
	if pageSize == 0 {
		pageSize = 20
	}
	if sortField == "" {
		sortField = "id"
	}
	if sortType == "" {
		sortType = "desc"
	}

	var total int64
	err := models.Region{}.GetTotalByParams(&models.Region{}, &total, params)
	if err != nil {
		return err
	}

	regions := []*pbRegion.Region{}
	regionItems := []models.Region{}
	if total > 0 {
		err := models.Region{}.GetResultsByParams(&models.Region{}, &regionItems, params, int(page), int(pageSize), sortField+" "+sortType)
		if err != nil {
			return err
		}

		for _, regionItem := range regionItems {
			regions = append(regions, &pbRegion.Region{
				Id:    uint32(regionItem.Id),
				Pid:   uint32(regionItem.Pid),
				Name:  regionItem.Name,
				Level: uint32(regionItem.Level),
				Sort:  uint32(regionItem.Sort),
				IsHot: int32(regionItem.IsHot),
			})
		}
	}

	pageTotal := math.Ceil(float64(total) / float64(pageSize))

	rsp.ListResult = &pbResult.ListCommonResult{
		Page:      page,
		Total:     uint32(total),
		PageSize:  uint32(pageSize),
		PageTotal: uint32(pageTotal),
	}
	rsp.Regions = regions
	return nil
}

/**
 * 单条区域信息
 *
 * @param string Name -----------------------------------------------------------------------非必传，名称
 * @return Brand error
 * @author huwl
 */
func (e *RegionHandler) Row(ctx context.Context, req *pbRegion.QueryRegionRequest, rsp *pbRegion.RegionResponse) error {
	params := map[string]interface{}{}

	if req.Name != "" {
		params["name"] = req.Name
	}
	if req.Pid != "all" {
		params["pid"] = req.Pid
	}
	if req.Name != "" {
		params["name"] = req.Name
	}
	if req.Level > 0 {
		params["level"] = req.Level
	}
	if req.IsHot != "all" {
		params["is_hot"] = req.IsHot
	}

	region := models.Region{}
	i, err := models.Region{}.Row(&models.Region{}, &region, params)
	if err != nil {
		return err
	}
	if i <= 0 {
		return errors.New("区域信息错误")
	}

	rsp.Region = &pbRegion.Region{
		Id:    uint32(region.Id),
		Pid:   uint32(region.Pid),
		Name:  region.Name,
		Level: uint32(region.Level),
		Sort:  uint32(region.Sort),
		IsHot: int32(region.IsHot),
	}
	return nil
}

/**
 * 多区域ID获取区域信息
 *
 * @param string ids ------------------------------------------------------------------------必传，区域ID多个
 * @return BrandItems error
 * @author huwl
 */
func (e *RegionHandler) Rows(ctx context.Context, req *pbParams.IdsRequest, rsp *pbRegion.RegionListResponse) error {
	ids := strings.TrimRight(req.Ids, ",")

	if ids == "" {
		return errors.New("区域ID错误")
	}

	regionIds := tools.IntSplit(ids, ",")
	regionItemIds := []interface{}{}
	for _, regionId := range regionIds {
		regionItemIds = append(regionItemIds, regionId)
	}

	regionItems := []models.Region{}
	err := models.Region{}.Rows(&regionItems, regionItemIds)
	if err != nil {
		return err
	}

	regions := []*pbRegion.Region{}
	for _, regionItem := range regionItems {
		regions = append(regions, &pbRegion.Region{
			Id:    uint32(regionItem.Id),
			Pid:   uint32(regionItem.Pid),
			Name:  regionItem.Name,
			Level: uint32(regionItem.Level),
			Sort:  uint32(regionItem.Sort),
			IsHot: int32(regionItem.IsHot),
		})
	}

	rsp.Regions = regions
	return nil
}
